import QtQuick 1.1
import com.nokia.symbian 1.1

Item {
    id: root
    property int visualX
    property Flickable myView
    property bool reloadTriggered
    property bool isHeader: false

    property int indicatorStart: 25
    property int refreshStart: 120

    property string pullDownMessage: qsTr("Pull to Refresh")
    property string releaseRefreshMessage: qsTr("Release to Refresh")

    signal refresh()

    width: 0
    height: parent ? parent.height : screen.height

    Connections {
        target: myView
        onContentXChanged: {
            if (isHeader){
                if (myView.atXBeginning){
                    var x = root.mapToItem(myView, 0, 0).x
                    if ( x < refreshStart + 20 )
                        visualX = x
                }
            } else {
                if (myView.atXEnd){
                    var x = root.mapToItem(myView, 0, 0).x
                    if ( myView.width - x < refreshStart + 20 )
                        visualX = myView.width - x
                }
            }
        }
    }

    Row {
        id: pswtrRow
        transform: Rotation {
            angle: 90
                origin.x: pswtrRow.height/2
                origin.y: pswtrRow.width/2
        }
        width: 0
        anchors.left: parent.right
        anchors.verticalCenter: parent.verticalCenter
        anchors.leftMargin: platformStyle.paddingLarge

        Image {
            visible: true//isHorizontal
            source:  window.useLightTheme ? "../../pics/pull_down_inverse.svg" : "../../pics/pull_down.svg"
            transform: Rotation {
                angle: 180
                origin.x: 15
                origin.y: 15
            }
            opacity: visualX < indicatorStart ? 0 : 1
            Behavior on opacity { NumberAnimation { duration: 100 } }
            rotation: {
                var newAngle = visualX
                if (newAngle > refreshStart && !myView.flicking){
                    root.reloadTriggered = true
                    return isHeader ? -180 : 0
                } else {
                    newAngle = newAngle > refreshStart ? 180 : 0
                    return isHeader ? -newAngle : newAngle - 180
                }
            }
            Behavior on rotation { NumberAnimation { duration: 150 } }
            onOpacityChanged: {
                if (opacity == 0 && root.reloadTriggered) {
                    root.reloadTriggered = false
                    root.refresh()
                }
            }
        }
        Label {
            text: root.reloadTriggered ? root.releaseRefreshMessage : root.pullDownMessage
            platformInverted: window.useLightTheme
        }
    }
}
